<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联任务" prop="taskId">
        <el-select v-model="queryParams.taskId" placeholder="请选择关联任务" clearable>
          <el-option v-for="task in taskList" :key="task.id" :label="task.taskName" :value="task.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="题目类型" prop="questionType">
        <el-select v-model="queryParams.questionType" placeholder="请选择题目类型" clearable>
          <el-option v-for="dict in dict.type.topic_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="难度等级" prop="difficulty">
        <el-select v-model="queryParams.difficulty" placeholder="请选择难度等级" clearable>
          <el-option v-for="dict in dict.type.topic_diff" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['demo:topic:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['demo:topic:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['demo:topic:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['demo:topic:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="topicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="关联培训任务" align="center" prop="taskId">
        <template slot-scope="scope">
          {{ getTaskName(scope.row.taskId) }}
        </template>
      </el-table-column>
      <el-table-column label="题目类型" align="center" prop="questionType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.topic_type" :value="scope.row.questionType" />
        </template>
      </el-table-column>
      <el-table-column label="题目标题" align="center" prop="content" />
      <!-- <el-table-column label="选项" align="center" prop="options" /> -->
      <el-table-column label="标准答案" align="center" prop="answer" />
      <el-table-column label="题目分值" align="center" prop="score" />
      <el-table-column label="难度等级" align="center" prop="difficulty">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.topic_diff" :value="scope.row.difficulty" />
        </template>
      </el-table-column>
      <el-table-column label="题目状态" align="center" prop="questionStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.topic_status" :value="scope.row.questionStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['demo:topic:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['demo:topic:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" /> -->

    <!-- 添加或修改培训考试题目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训任务" prop="taskId">
              <el-select v-model="form.taskId" placeholder="请选择关联培训任务" class="w100">
                <el-option v-for="task in taskList" :key="task.id" :label="task.taskName" :value="task.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目类型" prop="questionType">
              <el-radio-group v-model="form.questionType">
                <el-radio v-for="dict in dict.type.topic_type" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="题目分值" prop="score">
              <el-input v-model="form.score" placeholder="分值" />
            </el-form-item>
          </el-col>
          <el-col :span=7>
            <el-form-item label="题目状态" prop="questionStatus">
              <el-radio-group v-model="form.questionStatus">
                <el-radio v-for="dict in dict.type.topic_status" :key="dict.value" :label="parseInt(dict.value)">{{
                  dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度等级" prop="difficulty">
              <el-radio-group v-model="form.difficulty">
                <el-radio v-for="dict in dict.type.topic_diff" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider  content-position="left">整张试卷默认80分及格,根据及格线调整每题分值</el-divider>

        <el-form-item label="题目内容">
          <!-- <editor v-model="form.content" :min-height="192" /> -->
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" />

        </el-form-item>
        <el-form-item label="选项" prop="options">
          <el-row v-for="(option, index) in form.optionList" :key="index" :gutter="10" style="margin-bottom: 10px;">
            <el-col :span="4">
              <el-input v-model="option.value" placeholder="选项标识"></el-input>
            </el-col>
            <el-col :span="15">
              <el-input v-model="option.label" placeholder="选项内容"></el-input>
            </el-col>
            <el-col :span="4">
              <el-button @click="removeOption(index)" type="danger" icon="el-icon-delete" circle></el-button>
              <el-button v-if="index === form.optionList.length - 1" @click="addOption" type="primary"
                icon="el-icon-plus" circle></el-button>
            </el-col>
          </el-row>
          <el-button v-if="form.optionList.length === 0" @click="addOption" type="primary"
            icon="el-icon-plus">添加选项</el-button>
        </el-form-item>
        <el-form-item label="标准答案" prop="answer">
          <el-input v-model="form.answer" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="答案解析" prop="analysis">
          <el-input v-model="form.analysis" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTopic, listTopicForTask, getTopic, delTopic, addTopic, updateTopic } from "@/api/demo/topic/topic";
import { listTask } from "@/api/demo/task/task";

export default {
  name: "Topic",
  dicts: ['topic_type', 'topic_status', 'topic_diff'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 培训考试题目表格数据
      topicList: [],
      // 培训任务列表
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        questionType: null,
        content: null,
        difficulty: null,
        taskId: null
      },
      // 表单参数
      form: {
        optionList: []
      },
      // 表单校验
      rules: {
        questionType: [
          { required: true, message: "题目类型不能为空", trigger: "change" }
        ],
        content: [
          { required: true, message: "题目标题不能为空", trigger: "blur" }
        ],
        answer: [
          { required: true, message: "标准答案不能为空", trigger: "blur" }
        ],
        questionStatus: [
          { required: true, message: "题目状态不能为空", trigger: "change" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    // this.getList();
    this.getTaskList();
  },
  methods: {
    /** 查询培训考试题目列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.taskId == null) {
        return
      }
      listTopicForTask(this.queryParams).then(response => {
        this.topicList = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询培训任务列表 */
    getTaskList() {
      listTask().then(response => {
        this.taskList = response.rows;
        if (response.rows.length < 1) {
          return
        }
        this.queryParams.taskId = response.rows[0].id;
        this.getList()
      });
    },
    // 根据任务ID获取任务名称
    getTaskName(taskId) {
      const task = this.taskList.find(item => item.id === taskId);
      return task ? task.taskName : '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskId: this.queryParams.taskId,
        questionType: 1,
        content: null,
        options: null,
        optionList: [],
        answer: null,
        score: 5,
        difficulty: 1,
        questionStatus: 1,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加培训考试题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTopic(id).then(response => {
        this.form = response.data;
        // 解析选项字符串为数组
        try {
          this.form.optionList = JSON.parse(this.form.options || '[]');
        } catch (e) {
          this.form.optionList = [];
        }
        this.open = true;
        this.title = "修改培训考试题目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 将选项数组转换为JSON字符串
          this.form.options = JSON.stringify(this.form.optionList);
          if (this.form.id != null) {
            updateTopic(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTopic(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 添加选项
    addOption() {
      this.form.optionList.push({
        label: '',
        value: ''
      });
    },
    // 删除选项
    removeOption(index) {
      this.form.optionList.splice(index, 1);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除培训考试题目编号为"' + ids + '"的数据项？').then(function () {
        return delTopic(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('demo/topic/export', {
        ...this.queryParams
      }, `topic_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
